package models

import (
	"time"

	"gorm.io/gorm"
)

type UsersDao struct {
	Id          int       `gorm:"column:id;type:int(11);primary_key;AUTO_INCREMENT" json:"id"`
	Nickname    string    `gorm:"column:nickname;type:varchar(100);NOT NULL" json:"nickname"`
	Username    string    `gorm:"column:username;type:varchar(100);NOT NULL" json:"username"`
	Email       string    `gorm:"column:email;type:varchar(100);NOT NULL" json:"email"`
	Password    string    `gorm:"column:password;type:varchar(200);NOT NULL" json:"password"`
	Userintro   string    `gorm:"column:userintro;type:varchar(200);NOT NULL" json:"userintro"`
	Gender      string    `gorm:"column:gender;type:varchar(10);NOT NULL" json:"gender"`
	Createtime  int       `gorm:"column:createtime;type:int(30);NOT NULL" json:"createtime"`
	Agree       string    `gorm:"column:agree;type:varchar(10);NOT NULL" json:"agree"`
	HeadImgPath string    `gorm:"column:headImgPath;type:varchar(500)" json:"headImgPath"`
	Money       int       `gorm:"column:money;type:int(11);NOT NULL" json:"money"`
	CreatedAt   time.Time `gorm:"column:created_at;type:timestamp" json:"created_at"`
	UpdatedAt   time.Time `gorm:"column:updated_at;type:timestamp" json:"updated_at"`
}

func (s *UsersDao) TableName() string {
	return "users"
}

func (s *UsersDao) FindByIds(tx *gorm.DB, ids []int) ([]*UsersDao, error) {
	tx = tx.Model(&s)
	if len(ids) != 0 {
		tx = tx.Where("id in (?)", ids)
	}
	var list []*UsersDao
	if err := tx.Find(&list).Error; err != nil {
		return list, err
	}
	return list, nil
}

func (s *UsersDao) First(tx *gorm.DB) error {
	tx = tx.Model(&s)
	if s.Username != "" {
		tx = tx.Where("username = ?", s.Username)
	}
	if s.Password != "" {
		tx = tx.Where("password = ?", s.Password)
	}
	if s.Email != "" {
		tx = tx.Where("email = ?", s.Email)
	}
	if err := tx.Find(&s).Error; err != nil {
		return err
	}
	return nil
}

func (s *UsersDao) AddOne(tx *gorm.DB) error {
	tx = tx.Model(&s)
	if err := tx.Create(&s).Error; err != nil {
		return err
	}
	return nil
}

func (s *UsersDao) Update(tx *gorm.DB) error {
	tx = tx.Model(&s)
	if s.Email != "" {
		tx = tx.Where("email = ?", s.Email)
	}
	if err := tx.Updates(&s).Error; err != nil {
		return err
	}
	return nil
}
